#include "../StdInc.h"

namespace GSTrader
{
	namespace Indicator
	{
		VOL::VOL()
		{
			m_strIndicatorName = "VOL";
			m_nLines = 0;
			m_piLength = NULL;
			m_pResult->m_nStyle = 0;
		}


		VOL::~VOL()
		{

		}

		CIndicator* VOL::CreateInstance()
		{
			return new VOL;
		}

		void VOL::RefreshData()
		{
			if (m_pInput == NULL || m_pInput->m_nStartIndex < 0 || m_nLines <= 0 || m_piLength == NULL)
			{
				m_pResult->m_pDataSeries->m_nStartIndex = -1;
				for (int x = 0; x < m_nLines; x++)
				{
					m_vResult[x + 1]->m_pDataSeries->m_nStartIndex = -1;
				}

				return;
			}

			int nCount = m_pInput->GetCount();

			m_pResult->m_pDataSeries->SetSize(nCount, 0);

			size_t nSize = m_vResult.size();

			assert((int)nSize >= m_nLines);

			for (int x = 0; x < m_nLines; x++)
			{
				int nLength = m_piLength[x];

				int nStartIndex = nLength - 1;
				m_vResult[x + 1]->m_pDataSeries->SetSize(nCount, nStartIndex);
			}

			m_bCalc = true;
		}

		void VOL::SetParam(double* pdParam)
		{
			_delete(m_piLength);
			if (pdParam)
			{
				m_nLines = (int)pdParam[0];
				if (m_nLines > 0)
				{
					m_piLength = new int[m_nLines];
					for (int x = 0; x < m_nLines; x++)
					{
						m_piLength[x] = (int)pdParam[x + 1];
						if (m_piLength[x] < 0)
						{
							assert(false);
							m_piLength[x] = 0;
						}
					}
				}

				size_t nSize = m_vResult.size();
				for (int x = (int)nSize; x < m_nLines + 1; x++)
				{
					CIndicatorResult* pResult = new CIndicatorResult;
					m_vResult.push_back(pResult);
				}
			}

		}

		double VOL::Calculate(int nIndex)
		{
			if (m_nLines <= 0 || m_pInput->m_nStartIndex < 0 || m_piLength == NULL || m_pInput == NULL)
				return 0;

			double dVol = m_pInput->GetValue(nIndex, bdtVolume);
			m_pResult->SetValue(nIndex, dVol);
			for (int x = 0; x < m_nLines; x++)
			{
				CalcVolMa(nIndex, x, m_pResult->m_pDataSeries);
			}

			return 1;
		}

		void VOL::CalcVolMa(int nIndex, int nLineIndex, CDataSeries* pInput)
		{
			int nLength = m_piLength[nLineIndex];
			if (pInput == NULL || nLength <= 0)
				return;

			int nCount = pInput->GetCount();
			int nStartIndex = nIndex - nLength + 1;
			if (nStartIndex < 0 || nIndex >= nCount)
				return;

			int nEndIndex = nStartIndex + nLength;

			double dSum = 0, dValue;
			for (int x = nStartIndex; x < nEndIndex; x++)
			{
				dSum += pInput->GetValue(x, bdtClose);
			}

			dValue = dSum / nLength;
			m_vResult[nLineIndex + 1]->SetValue(nIndex, dValue);
		}
	}
}